import { createRouter, createWebHistory } from 'vue-router';

import { useGlobalStore } from '../store';

import LayoutIndex from '../views/layout/LayoutIndex.vue';
import UsersLogin from '../views/users/UsersLogin.vue';

const routes = [
  {
    path: '/',
    redirect: { name: 'UsersLogin' },
  },
  {
    path: '/login',
    component: UsersLogin,
    name: 'UsersLogin',
  },
  {
    path: '/rules',
    component: LayoutIndex,
    name: 'Rules',
    children: [
      {
        path: 'index',
        name: 'RulesIndex',
        component: () => import('../views/rules/RulesIndex.vue'),
        meta: {
          menuName: '权限管理',
        },
      }, {
        path: 'add',
        name: 'RulesAdd',
        component: () => import('../views/rules/RulesAdd.vue'),
        meta: {
          menuName: '添加权限',
        },
      },
    ],
  },
  {
    path: '/users',
    component: LayoutIndex,
    name: 'Users',
    children: [
      {
        path: 'index',
        name: 'UsersIndex',
        component: () => import('../views/users/UsersIndex.vue'),
        meta: {
          menuName: '用户管理',
        },
      },
      {
        path: 'add',
        name: 'UsersAdd',
        component: () => import('../views/users/UsersAdd.vue'),
        meta: {
          menuName: '添加新用户',
        },
      },
      {
        path: 'edit',
        name: 'UsersEdit',
        component: () => import('../views/users/UsersEdit.vue'),
        meta: {
          menuName: '用户编辑',
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const GlobalStore = useGlobalStore();
  if (to.name === 'UsersLogin') {
    if (GlobalStore.authorization === '') {
      next();
    } else {
      next({ name: 'UsersIndex' });
    }
  } else if (GlobalStore.authorization === '') {
    next({ name: 'UsersLogin' });
  } else {
    next();
  }
});

export default router;
